<template>
  <div>
    <h3 class="text-lg font-semibold mb-3 dark:text-white">群组邀请</h3>
    
    <div v-if="loading" class="text-center py-6">
      <div class="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-indigo-500 mx-auto"></div>
      <p class="mt-2 text-sm text-gray-500 dark:text-gray-400">加载邀请中...</p>
    </div>
    
    <div v-else-if="invitations.length === 0" class="text-center py-6 text-gray-500 dark:text-gray-400">
      暂无群组邀请
    </div>
    
    <div v-else class="space-y-3">
      <div 
        v-for="invitation in invitations" 
        :key="invitation.id"
        class="bg-white dark:bg-gray-800 rounded-lg shadow p-4"
      >
        <div class="flex items-start justify-between">
          <div class="flex items-center space-x-3">
            <div class="text-2xl">{{ processGroupAvatar(invitation.group.group_avatar) }}</div>
            <div>
              <h4 class="font-medium dark:text-white">{{ invitation.group.name }}</h4>
              <p class="text-sm text-gray-500 dark:text-gray-400">
                来自: {{ invitation.inviter.username }}
              </p>
            </div>
          </div>
          <span class="text-xs bg-blue-100 text-blue-800 py-1 px-2 rounded-full dark:bg-blue-900 dark:text-blue-200">
            {{ formatDate(invitation.created_at) }}
          </span>
        </div>
        
        <p v-if="invitation.group.description" class="mt-2 text-sm text-gray-600 dark:text-gray-300">
          {{ invitation.group.description }}
        </p>
        
        <div class="flex space-x-2 mt-3">
          <button 
            @click="handleInvitation(invitation.id, 'accepted')"
            :disabled="invitation.processingAccept"
            class="flex-1 px-3 py-1.5 text-sm font-medium text-white bg-green-600 hover:bg-green-700 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 disabled:opacity-50"
          >
            {{ invitation.processingAccept ? '处理中...' : '接受' }}
          </button>
          <button 
            @click="handleInvitation(invitation.id, 'rejected')"
            :disabled="invitation.processingReject"
            class="flex-1 px-3 py-1.5 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600 disabled:opacity-50"
          >
            {{ invitation.processingReject ? '处理中...' : '拒绝' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { useToast } from 'vue-toastification';
import axios from 'axios';

export default {
  name: 'GroupInvitations',
  emits: ['invitation-responded'],
  setup(props, { emit }) {
    const toast = useToast();
    const invitations = ref([]);
    const loading = ref(true);
    
    const loadInvitations = async () => {
      try {
        loading.value = true;
        const response = await axios.get('/api/groups/invitations');
        invitations.value = response.data.map(inv => ({
          ...inv,
          processingAccept: false,
          processingReject: false
        }));
      } catch (err) {
        console.error('加载群组邀请失败:', err);
        toast.error('无法加载群组邀请');
      } finally {
        loading.value = false;
      }
    };
    
    const handleInvitation = async (invitationId, action) => {
      const invitation = invitations.value.find(inv => inv.id === invitationId);
      if (!invitation) return;
      
      if (action === 'accepted') {
        invitation.processingAccept = true;
      } else {
        invitation.processingReject = true;
      }
      
      try {
        await axios.put(`/api/groups/invitations/${invitationId}`, { action });
        
        // 从列表中移除这个邀请
        invitations.value = invitations.value.filter(inv => inv.id !== invitationId);
        
        toast.success(action === 'accepted' ? '已加入群组' : '已拒绝邀请');
        emit('invitation-responded', { invitationId, action });
      } catch (err) {
        console.error('处理邀请失败:', err);
        toast.error(err.response?.data?.message || '处理邀请失败');
        
        if (action === 'accepted') {
          invitation.processingAccept = false;
        } else {
          invitation.processingReject = false;
        }
      }
    };
    
    const formatDate = (dateString) => {
      if (!dateString) return '';
      
      const date = new Date(dateString);
      const now = new Date();
      const diffDays = Math.floor((now - date) / (1000 * 60 * 60 * 24));
      
      if (diffDays === 0) {
        return '今天';
      } else if (diffDays === 1) {
        return '昨天';
      } else if (diffDays < 7) {
        return `${diffDays}天前`;
      } else {
        return `${date.getMonth() + 1}月${date.getDate()}日`;
      }
    };
    
    const processGroupAvatar = (avatar) => {
      if (!avatar) return '👥'
      
      // 如果包含emoji前缀，去除前缀
      if (avatar.startsWith('emoji:')) {
        return avatar.replace('emoji:', '')
      }
      
      // 如果是图片URL，返回默认emoji（因为这里是纯文本显示）
      if (avatar.startsWith('data:image/') || avatar.startsWith('http')) {
        return '👥'
      }
      
      // 直接返回emoji
      return avatar || '👥'
    };
    
    onMounted(loadInvitations);
    
    return {
      invitations,
      loading,
      handleInvitation,
      formatDate,
      processGroupAvatar
    };
  }
};
</script> 